<template>
  <div id="scoketInfo">
    <!-- <el-button @click="go()">拒 绝</el-button> -->

    <el-dialog title="会诊通知" :visible.sync="dialogVisible" width="30%" :show-close="false" :close-on-click-modal="false" :close-on-press-escape="false" :append-to-body="false">
      <!-- fullscreen="true" -->
      <!-- :before-close="handleClose" -->
      <span>医生”{{ doctorName }}“邀请您加入患者”{{ patientName }}“的会诊</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="refuseInvite()">拒 绝</el-button>
        <el-button type="primary" @click="acceptInvite()">接 受</el-button>
      </span>
    </el-dialog>
    <el-dialog title="归档信息提示" :visible.sync="archiveDialogVisible" width="50%" center>
      <span v-html="archiveHtml" />
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="archiveDialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="归档提前通知" :visible.sync="advanceInformDialogVisible" width="50%" center>
      <span v-html="advanceInformHtml" />
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="advanceInformDialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="导管室通知" :visible.sync="conduitRoomDialogVisible" width="50%" center>
      <span>
        {{ conduitRoomData.doctorName }} 医生下达对患者 {{ conduitRoomData.patientName }} 启动导管室的治疗决定
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="conduitRoomBusyDialogVisible=true">导管室占台</el-button>
        <el-button type="primary" @click="clcsStartCrFun()">立即启动</el-button>
      </span>
      <el-dialog
        width="30%"
        title="导管室占台通知"
        :visible.sync="conduitRoomBusyDialogVisible"
        append-to-body
      >
        <span>
          <label for="CRBusy">预计占台时间： </label>
          <el-date-picker
            id="CRBusy"
            v-model="conduitRoomBusyTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择占台时间"
          />
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="conduitRoomBusyDialogVisible=true">取 消</el-button>
          <el-button type="primary" @click="clcsNoticeTimeFun()">确 定</el-button>
        </span>
      </el-dialog>
    </el-dialog>

  </div>
</template>
<script>
// import { mapGetters } from 'vuex'
// import Logo from './Logo'
// import SidebarItem from './SidebarItem'
// import variables from '@/styles/variables.scss'
// import { SocketMount } from '@/socket'

// import io from 'socket.io-client'
import { sendRefuseInvite, sendAcceptInvite, clcsStartCr, clcsNoticeTime } from '@/api/socket'
export default {
  // components: { SidebarItem, Logo },
  data() {
    return {
      webSocket: {},
      dialogVisible: false,
      archiveDialogVisible: false, // 归档信息提示
      advanceInformDialogVisible: false, //  "归档提前通知
      conduitRoomDialogVisible: false, //  "导管室通知
      conduitRoomBusyDialogVisible: false, //  "导管室占台

      nameArr: [], // 会诊相关数据
      doctorName: '',
      patientName: '',
      archiveHtml: '', // 归档通知内容
      advanceInformHtml: '', // 提前通知内容
      consulting: null, // 当前会诊患者信息
      conduitRoomData: {
        doctorName: '',
        patientName: '',
        initiatorId: '',
        dispatchId: ''
      },
      conduitRoomBusyTime: ''
    }
  },
  mounted() {
    this.SocketMount()
  },
  destroyed() {
    this.webSocket.close()
    console.log('会诊webSocket关闭')
  },
  methods: {
    clcsNoticeTimeFun() {
      const data = {
        apiToken: this.$store.getters.apiToken,
        time: this.conduitRoomBusyTime,
        touserId: this.conduitRoomData.initiatorId
      }
      clcsNoticeTime(data).then(res => {
        if (res.code === 0) {
          this.$message.success('通知发送成功')
          this.conduitRoomBusyDialogVisible = false
          this.conduitRoomDialogVisible = false
          this.clearConduitRoom()
        } else {
          this.$message.error('导管室占台异常')
        }
      }).catch(err => {
        console.log(err)
      })
    },

    clearConduitRoom() {
      this.conduitRoomData = {
        doctorName: '',
        patientName: '',
        initiatorId: '',
        dispatchId: ''
      }
      this.conduitRoomBusyTime = ''
    },
    // 立即启动导管室
    clcsStartCrFun() {
      const data = {
        apiToken: this.$store.getters.apiToken,
        dispatchId: this.conduitRoomData.dispatchId,
        userStr: this.conduitRoomData.initiatorId
      }
      clcsStartCr(data).then(res => {
        if (res.code === 0) {
          this.$message.info('同意启动导管室')
          this.conduitRoomDialogVisible = false
          this.clearConduitRoom()
        } else {
          this.$message.error('启动导管室请求异常')
        }
      }).catch(err => {
        console.log(err)
      })
    },

    // handleClose(e, a) {
    //   console.log(e, a)
    // },
    refuseInvite() {		// 拒绝会诊邀请
      const refuseData = {
        'apiToken': this.$store.getters.apiToken,
        'consultationsId': this.$store.getters.consultationsId
      }
      sendRefuseInvite(refuseData).then(res => {
        console.log('拒绝会诊邀请', res)
        this.dialogVisible = false
        this.$message('会诊已拒绝')
        // console.log(res)
      })
      // /*   跳转页面    */
      // this.$store.commit('user/SET_CONSULTATIONSID', this.nameArr[2]) // 存储会诊标识CONSULTATIONSID
      // this.$store.commit('user/SET_DATABUS', {
      //   dispatchId: this.nameArr[3],
      //   diseaseType: '胸痛',
      //   patientId: this.nameArr[4]
      // })
      // console.log(this.$store.getters.dataBus)
      // const currentPageName = this.$route.name
      // if (currentPageName === 'patientsList') {
      //   this.$router.push({ path: '/redirect/green-channel/patients-list' })
      // } else {
      //   this.$router.push({ path: '/green-channel/patients-list' })
      // }
      /*   跳转页面    */
    },
    //    页面跳转
    pageJumps(pageName, data) {
      this.$router.push({
        name: 'patientsList',
        params: data,
        query: {
          t: +new Date() // 保证每次点击路由的query项都是不一样的，确保会重新刷新view
        }
      })
    },
    /*
      *接受会诊邀请
    */
    acceptInvite() {
      const acceptData = {
        'apiToken': this.$store.getters.apiToken,
        'consultationsId': this.$store.getters.consultationsId,
        'userIdStr': this.nameArr[this.nameArr.length - 1]
      }
      sendAcceptInvite(acceptData).then(res => {
        this.dialogVisible = false
        let data = {}
        if (res.code === 0) {
          data = res.data
          data.sourcePage = 'Socket'
          this.consulting = data
          this.pageJumps("'patientsList'", this.consulting)
          // this.$router.push({
          //   name: 'patientsList',
          //   params: data,
          //   query: {
          //     t: +new Date() // 保证每次点击路由的query项都是不一样的，确保会重新刷新view
          //   }
          // })
          console.log('同意会诊邀请', data)
        } else {
          this.$message.error('服务器错误')
          console.log('同意会诊-s错误', res)
        }
        // row.patientId = row.pid

        // console.log(res)
      })
    },

    successTips(tips) {
      this.$message({
        message: tips,
        type: 'success'
      })
    },
    warningTips(tips) {
      this.$message({
        message: tips,
        type: 'warning'
      })
    },

    /*
      * 建立WebSocket连接
    */
    SocketMount() {
      const url = process.env.VUE_APP_ENV_ADDRESS?process.env.VUE_APP_ENV_ADDRESS.replace('http', 'ws') + ':12334':""
      const socketUrl = `${url}/websocket/${this.$store.getters.userId}`
      // 本地测试使用
      // socketUrl = 'ws://192.168.2.120/websocket/' + this.$store.getters.userId
      this.webSocket = new WebSocket(socketUrl)
      /* 建立连接*/
      this.webSocket.onopen = (evt) => {
        console.log('webSocket通知连接成功')
      }
      /* 连接关闭*/
      this.webSocket.onclose = (evt) => {
        console.log('webSocket通知连接关闭')
      }
      /* 接收服务器推送消息*/
      this.webSocket.onmessage = (data) => {
        console.log('webSocket接收数据:', data)
        try {
          data = JSON.parse(data.data)
        } catch (e) {
          this.$message.warning('获取webSocket消息出错')
          // TODO handle the exception
        }
        /*
          * 无data.model判断为会诊
        */
        if (!data.model) {
          this.consultation_Info(data)
          return false
        } else if (data.model === '处理措施通知导管室') {
          this.conduitRoom_Info(data)
        } else {
          // console.log('归档数据', data.mapcontent)
          let tipStr = ''
          if (data.model === '自动归档') {
            if (data.mapcontent.length > 0) {
              if (data.mapcontent[0].infotime) { // 有infotime为提前通知消息
                data.mapcontent.forEach(item => {
                  tipStr += `<div class="mg-10"><b>${item.modelName}</b> 中的 <b>${item.patientName || '未命名患者'}</b> 将在 <b>${item.infotime}</b> 天后根据归档设置自动纳入“归档”列表中！</div>`
                })
                this.advanceInformHtml = tipStr
                this.advanceInformDialogVisible = true
              } else { // 无infotime为归档后通知消息
                data.mapcontent.forEach(item => {
                  tipStr += `<div class="mg-10"><b>${item.modelName}</b> 中的 <b>${item.patientName || '未命名患者'}</b> 已根据归档设置自动纳入“归档”列表中！</div>`
                })
                if (tipStr !== '') {
                  this.archiveHtml = tipStr
                  this.archiveDialogVisible = true
                }
              }
            } else {
              return false
            }
          } else if (data.model === '手动归档') {
            data.mapcontent.forEach(item => {
              tipStr += `<div class="mg-10"><b>${item.modelName}</b> 中的 <b>${item.patientName}</b> 已由 <b>${item.patientName}</b> 手动纳入“归档”列表中！</div>`
            })
            this.archiveHtml = tipStr
            this.archiveDialogVisible = true
          }
        }
      }
      /* 连接发生错误时*/
      this.webSocket.onerror = (evt, e) => {
        console.log('会诊通知webSocket连接错误')
        console.log(evt)
        this.webSocket.open()
      }
      // webSocket.close()
    },

    /*
     *     导管室信息处理
    */
    conduitRoom_Info(data) {
      const content = data.content
      const splitLastIndex = content.lastIndexOf('@')
      const functionName = content.substr(1, splitLastIndex - 1)
      // const infoArr = content.substr(splitLastIndex + 1).split('~')
      if (functionName === 'clcsNoticeCr') {
        const [doctorName, patientName, initiatorId, dispatchId] = content.substr(splitLastIndex + 1).split('~')
        this.conduitRoomData = { doctorName, patientName, initiatorId, dispatchId }
        this.conduitRoomDialogVisible = true
      } else if (functionName === 'clcsStartCr') {
        this.$message.success('导管室启动成功')
      } else if (functionName === 'clcsNoticeTime') {
        this.$message({
          showClose: true,
          message: content.substr(splitLastIndex + 1),
          duration: 0
        })
      }
    },

    /*
     *     会诊信息处理
    */
    consultation_Info(data) {
      // 会诊
      // console.log(data)
      let content = null
      // if (data.data && JSON.parse(data.data)) {
      //   content = JSON.parse(data.data).content
      // }
      content = data.content
      if (!content) {
        console.log('会诊信息接收错误')
        return false
      }
      const splitLastIndex = content.lastIndexOf('@')
      const functionName = content.substr(1, splitLastIndex - 1)
      this.nameArr = content.substr(splitLastIndex + 1).split('~')

      /*
        * 对方接受时的反馈
      */
      if (functionName === 'acceptConsultations') {
        this.$message({
          message: '医生: ' + this.nameArr[0] + ' 接受了 患者: ' + this.nameArr[1] + ' 的会诊',
          type: 'success'
        })
      } else if (functionName === 'refuseConsultations') { // 对方拒绝时的反馈
        this.$message({
          message: '医生: ' + this.nameArr[0] + ' 拒绝了 患者: ' + this.nameArr[1] + ' 的会诊',
          type: 'warning'
        })
      } else if (functionName === 'inviteConsultations' || functionName === 'startConsultations') { // 收到他人邀请
        this.$store.commit('user/SET_CONSULTATIONSID', this.nameArr[2]) // 存储会诊标识CONSULTATIONSID
        this.doctorName = this.nameArr[0]
        this.patientName = this.nameArr[1]
        console.log(this.$store.getters.consultationsId)
        this.dialogVisible = true
      } else if (functionName === 'sendChangeMessage') { // 发生更改更新基本信息页面
        console.log('-----sendChangeMessage--', this.nameArr, data)
        // $('#content-id').contents().find('#iframe3').attr('src', 'http://xzyl.seiohealth.com/profile?action=basic_info&dispatchId=' + this.nameArr[this.nameArr.length - 1])
        this.pageJumps("'patientsList'", this.consulting)
        this.$message({
          message: '医生: ' + this.nameArr[0] + ' 更新了 患者: ' + this.nameArr[1] + ' 的会诊消息',
          type: 'warning'
        })
      } else if (functionName === 'exitConsultations') { // 结束反馈
        this.$message({
          message: '医生: ' + this.nameArr[0] + ' 结束了 患者: ' + this.nameArr[1] + ' 的会诊',
          type: 'warning'
        })
        this.nameArr = []
        this.$store.commit('user/SET_CONSULTATIONSID', '') // 存储会诊标识CONSULTATIONSID
        this.$store.commit('user/SET_DATABUS', {})
      }
      return
    }
  }
}
</script>
